import store from '@/store'
import router from '@/router'
export default function () {
    let routers = store.state.user.routers 
    return new Promise((resolve)=>{
        let asyncRouters = filterRouter(routers)
        asyncRouters.forEach(item => {
            router.addRoute(item)
        })
        resolve()
    })
}

// 递归处理路由
function filterRouter(routers) { // 遍历后台传来的路由字符串，转换为组件对象
    return routers.filter(item => {
        if (!item.component) return false
        if (item.component === 'Layout') {
            // 一级目录
            item.component = _ => import('@/views/layout')
        } else if (item.component === 'ParentView') {
            // 处理中间层级目录
            item.component = _ => import('@/views/ParentView')
        } else {
            // 视为最终页面
            let view = item.component
            item.component = (resolve) => require([`@/pages/${view}`], resolve)
        }
        if (item.children && item.children.length) filterRouter(item.children)
        return true
    })
}